package com.funsport.controller.mobile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.Result;
import com.funsport.entity.CommunityPost;
import com.funsport.entity.User;
import com.funsport.service.ICommunityPostService;
import com.funsport.service.IUserService;
import com.funsport.service.IFriendService;
import com.funsport.service.IPointsService;
import com.funsport.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 移动端社区控制器
 */
@RestController
@RequestMapping("/mobile/community")
@Slf4j
public class MobileCommunityController {

    @Autowired
    private ICommunityPostService communityPostService;

    @Autowired
    private IUserService userService;
    
    @Autowired
    private IFriendService friendService;
    
    @Autowired
    private IPointsService pointsService;
    
    @Autowired
    private com.funsport.service.WechatSecurityService securityService;

    /**
     * 获取帖子列表
     */
    @GetMapping("/posts")
    public Result<Map<String, Object>> getPostList(@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(required = false) String postType) {
        try {
            // 创建分页对象
            Page<CommunityPost> pageObj = new Page<>(page, pageSize);
            
            // 构建查询条件
            LambdaQueryWrapper<CommunityPost> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPost::getStatus, "published"); // 只查询已发布的帖子
            
            if (postType != null && !postType.isEmpty()) {
                wrapper.eq(CommunityPost::getPostType, postType);
            }
            
            // 按创建时间倒序排列
            wrapper.orderByDesc(CommunityPost::getCreatedAt);
            
            // 执行分页查询
            IPage<CommunityPost> result = communityPostService.page(pageObj, wrapper);
            
            // 获取帖子列表
            List<CommunityPost> posts = result.getRecords();
            
            // 获取作者信息
            List<Long> authorIds = posts.stream()
                    .map(CommunityPost::getAuthorId)
                    .distinct()
                    .collect(Collectors.toList());
            
            final Map<Long, User> authorMap;
            if (!authorIds.isEmpty()) {
                List<User> authors = userService.listByIds(authorIds);
                authorMap = authors.stream()
                        .collect(Collectors.toMap(User::getId, user -> user));
            } else {
                authorMap = new HashMap<>();
            }
            
            // 组装返回数据
            List<Map<String, Object>> postList = posts.stream().map(post -> {
                Map<String, Object> postMap = new HashMap<>();
                postMap.put("id", post.getId());
                postMap.put("title", post.getTitle());
                postMap.put("content", post.getContent());
                postMap.put("postType", post.getPostType());
                postMap.put("images", post.getImages());
                postMap.put("likeCount", post.getLikeCount());
                postMap.put("commentCount", post.getCommentCount());
                postMap.put("viewCount", post.getViewCount());
                postMap.put("createdAt", post.getCreatedAt());
                
                // 作者信息
                User author = authorMap.get(post.getAuthorId());
                if (author != null) {
                    Map<String, Object> authorInfo = new HashMap<>();
                    authorInfo.put("id", author.getId());
                    authorInfo.put("nickname", author.getNickname());
                    authorInfo.put("avatarUrl", author.getAvatar());
                    postMap.put("author", authorInfo);
                }
                
                return postMap;
            }).collect(Collectors.toList());
            
            // 返回分页结果
            Map<String, Object> response = new HashMap<>();
            response.put("list", postList);
            response.put("total", result.getTotal());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("pages", result.getPages());
            
            return Result.success(response);
            
        } catch (Exception e) {
            log.error("获取帖子列表失败", e);
            return Result.error("获取帖子列表失败");
        }
    }
    
    /**
     * 获取关注用户的帖子列表
     */
    @GetMapping("/posts/following")
    public Result<Map<String, Object>> getFollowingPosts(@RequestParam(defaultValue = "1") Integer page,
                                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            // 获取关注的用户列表
            List<User> followingUsers = friendService.getFriendList(userId);
            
            if (followingUsers.isEmpty()) {
                // 没有关注任何人，返回空列表
                Map<String, Object> response = new HashMap<>();
                response.put("list", new ArrayList<>());
                response.put("total", 0);
                response.put("current", page);
                response.put("size", pageSize);
                response.put("pages", 0);
                return Result.success(response);
            }
            
            List<Long> followingUserIds = followingUsers.stream()
                    .map(User::getId)
                    .collect(Collectors.toList());
            
            // 创建分页对象
            Page<CommunityPost> pageObj = new Page<>(page, pageSize);
            
            // 构建查询条件：只查询关注用户的帖子
            LambdaQueryWrapper<CommunityPost> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPost::getStatus, "published");
            wrapper.in(CommunityPost::getAuthorId, followingUserIds);
            wrapper.orderByDesc(CommunityPost::getCreatedAt);
            
            // 执行分页查询
            IPage<CommunityPost> result = communityPostService.page(pageObj, wrapper);
            
            // 组装返回数据（复用之前的逻辑）
            List<CommunityPost> posts = result.getRecords();
            List<Map<String, Object>> postList = buildPostList(posts, followingUsers);
            
            Map<String, Object> response = new HashMap<>();
            response.put("list", postList);
            response.put("total", result.getTotal());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("pages", result.getPages());
            
            return Result.success(response);
            
        } catch (Exception e) {
            log.error("获取关注帖子列表失败", e);
            return Result.error("获取关注帖子列表失败");
        }
    }
    
    /**
     * 获取热门帖子列表（浏览量>100）
     */
    @GetMapping("/posts/hot")
    public Result<Map<String, Object>> getHotPosts(@RequestParam(defaultValue = "1") Integer page,
                                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            // 创建分页对象
            Page<CommunityPost> pageObj = new Page<>(page, pageSize);
            
            // 构建查询条件：浏览量>100
            LambdaQueryWrapper<CommunityPost> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPost::getStatus, "published");
            wrapper.gt(CommunityPost::getViewCount, 100); // 浏览量大于100
            wrapper.orderByDesc(CommunityPost::getViewCount); // 按浏览量倒序
            wrapper.orderByDesc(CommunityPost::getCreatedAt); // 再按时间倒序
            
            // 执行分页查询
            IPage<CommunityPost> result = communityPostService.page(pageObj, wrapper);
            
            // 获取帖子列表
            List<CommunityPost> posts = result.getRecords();
            
            // 获取作者信息
            List<Long> authorIds = posts.stream()
                    .map(CommunityPost::getAuthorId)
                    .distinct()
                    .collect(Collectors.toList());
            
            final Map<Long, User> authorMap;
            if (!authorIds.isEmpty()) {
                List<User> authors = userService.listByIds(authorIds);
                authorMap = authors.stream()
                        .collect(Collectors.toMap(User::getId, user -> user));
            } else {
                authorMap = new HashMap<>();
            }
            
            // 组装返回数据
            List<Map<String, Object>> postList = posts.stream().map(post -> {
                Map<String, Object> postMap = new HashMap<>();
                postMap.put("id", post.getId());
                postMap.put("title", post.getTitle());
                postMap.put("content", post.getContent());
                postMap.put("postType", post.getPostType());
                postMap.put("images", post.getImages());
                postMap.put("likeCount", post.getLikeCount());
                postMap.put("commentCount", post.getCommentCount());
                postMap.put("viewCount", post.getViewCount());
                postMap.put("createdAt", post.getCreatedAt());
                
                // 作者信息
                User author = authorMap.get(post.getAuthorId());
                if (author != null) {
                    Map<String, Object> authorInfo = new HashMap<>();
                    authorInfo.put("id", author.getId());
                    authorInfo.put("nickname", author.getNickname());
                    authorInfo.put("avatarUrl", author.getAvatar());
                    postMap.put("author", authorInfo);
                }
                
                return postMap;
            }).collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("list", postList);
            response.put("total", result.getTotal());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("pages", result.getPages());
            
            return Result.success(response);
            
        } catch (Exception e) {
            log.error("获取热门帖子列表失败", e);
            return Result.error("获取热门帖子列表失败");
        }
    }
    
    /**
     * 辅助方法：构建帖子列表
     */
    private List<Map<String, Object>> buildPostList(List<CommunityPost> posts, List<User> users) {
        final Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        
        return posts.stream().map(post -> {
            Map<String, Object> postMap = new HashMap<>();
            postMap.put("id", post.getId());
            postMap.put("title", post.getTitle());
            postMap.put("content", post.getContent());
            postMap.put("postType", post.getPostType());
            postMap.put("images", post.getImages());
            postMap.put("likeCount", post.getLikeCount());
            postMap.put("commentCount", post.getCommentCount());
            postMap.put("viewCount", post.getViewCount());
            postMap.put("createdAt", post.getCreatedAt());
            
            // 作者信息
            User author = userMap.get(post.getAuthorId());
            if (author != null) {
                Map<String, Object> authorInfo = new HashMap<>();
                authorInfo.put("id", author.getId());
                authorInfo.put("nickname", author.getNickname());
                authorInfo.put("avatarUrl", author.getAvatar());
                postMap.put("author", authorInfo);
            }
            
            return postMap;
        }).collect(Collectors.toList());
    }

    /**
     * 获取帖子详情
     */
    @GetMapping("/posts/{id}")
    public Result<Map<String, Object>> getPostDetail(@PathVariable Long id) {
        try {
            CommunityPost post = communityPostService.getById(id);
            if (post == null) {
                return Result.error("帖子不存在");
            }
            
            // 增加浏览量
            post.setViewCount(post.getViewCount() + 1);
            communityPostService.updateById(post);
            
            // 获取作者信息
            User author = userService.getById(post.getAuthorId());
            
            // 组装返回数据
            Map<String, Object> postMap = new HashMap<>();
            postMap.put("id", post.getId());
            postMap.put("title", post.getTitle());
            postMap.put("content", post.getContent());
            postMap.put("postType", post.getPostType());
            postMap.put("images", post.getImages());
            postMap.put("likeCount", post.getLikeCount());
            postMap.put("commentCount", post.getCommentCount());
            postMap.put("viewCount", post.getViewCount());
            postMap.put("createdAt", post.getCreatedAt());
            
            if (author != null) {
                Map<String, Object> authorInfo = new HashMap<>();
                authorInfo.put("id", author.getId());
                authorInfo.put("nickname", author.getNickname());
                authorInfo.put("avatarUrl", author.getAvatar());
                postMap.put("author", authorInfo);
            }
            
            return Result.success(postMap);
            
        } catch (Exception e) {
            log.error("获取帖子详情失败: id={}", id, e);
            return Result.error("获取帖子详情失败");
        }
    }

    /**
     * 创建帖子
     */
    @PostMapping("/posts")
    public Result<String> createPost(@RequestBody CommunityPost post) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return Result.error("请先登录");
            }
            
            // 内容安全检测 - 检测标题
            if (post.getTitle() != null && !securityService.checkText(post.getTitle())) {
                log.warn("帖子标题包含违规内容: userId={}", userId);
                return Result.error("标题包含违规内容，请修改后重试");
            }
            
            // 内容安全检测 - 检测内容
            if (post.getContent() != null && !securityService.checkText(post.getContent())) {
                log.warn("帖子内容包含违规内容: userId={}", userId);
                return Result.error("内容包含违规内容，请修改后重试");
            }
            
            // 内容安全检测 - 检测图片
            if (post.getImages() != null && !post.getImages().trim().isEmpty()) {
                String[] imageUrls = post.getImages().split(",");
                if (!securityService.checkImages(imageUrls)) {
                    log.warn("帖子图片包含违规内容: userId={}", userId);
                    return Result.error("图片包含违规内容，请重新上传");
                }
            }
            
            // 检查是否是第一次发帖
            long postCount = communityPostService.count(
                new LambdaQueryWrapper<CommunityPost>()
                    .eq(CommunityPost::getAuthorId, userId)
            );
            boolean isFirstPost = (postCount == 0);
            
            post.setAuthorId(userId);
            post.setStatus("published");
            post.setLikeCount(0);
            post.setCommentCount(0);
            post.setViewCount(0);
            
            boolean success = communityPostService.save(post);
            if (success) {
                // 第一次发帖奖励积分
                if (isFirstPost) {
                    try {
                        pointsService.addUserPoints(userId, 10, "首次发布帖子", null, null);
                        log.info("首次发帖奖励积分: userId={}, postId={}", userId, post.getId());
                    } catch (Exception e) {
                        log.error("首次发帖奖励积分失败: userId={}, postId={}", userId, post.getId(), e);
                    }
                }
                return Result.success("发布成功");
            } else {
                return Result.error("发布失败");
            }
            
        } catch (Exception e) {
            log.error("创建帖子失败", e);
            return Result.error("发布失败");
        }
    }

    /**
     * 点赞/取消点赞帖子
     */
    @PostMapping("/posts/{id}/like")
    public Result<String> toggleLike(@PathVariable Long id) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return Result.error("请先登录");
            }
            
            boolean success = communityPostService.toggleLike(id, userId);
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("操作失败");
            }
            
        } catch (Exception e) {
            log.error("点赞操作失败: postId={}", id, e);
            return Result.error("操作失败");
        }
    }
}
